<?php

namespace App\Controllers;

use Framework\Database;
use Framework\Validation;
use Framework\Session;

class UserController
{
    protected $db;

    public function __construct()
    {
        $config = require basePath('config/db.php');
        $this->db = new Database($config);
    }

    /**
     * 显示登录页面
     */
    public function login()
    {
        //加载登录页面的视图
        loadView('users/login');
    }

    /**
     * 显示注册页面
     */

    public function create()
    {
        //加载创建用户
        loadView('users/create');
    }

    /**
     * 将用户数据存储到数据库中
     */
    public function store()
    {
        //从POST请求在获取数据
        $name = $_POST['name'];
        $email = $_POST['email'];
        $city = $_POST['city'];
        $province = $_POST['province'];
        $password = $_POST['password'];
        $passwordConfirmation = $_POST['password_confirmation'];

        //初始化
        $errors = [];
        //验证电子邮件是否有效
        if (!Validation::email($email)) {
            $errors['email'] = '请输入一个合法的电子邮件地址!';
        }

        if (!Validation::string($name, 2, 50)) {
            $errors['name'] = '姓名长度为2到50! ';
        }

        if (!Validation::string($password, 6, 50)) {
            $errors['password'] = '密码长度为至少6位! ';
        }

        if (!Validation::match($password, $passwordConfirmation)) {
            $errors['password_confirmation'] = '两次的输入密码不一致! ';
        }
        //检查是否存在验证错误
        if (!empty($errors)) {
            loadView('users/create', [
                'errors' => $errors,
                'user' => [
                    'name' => $name,
                    'email' => $email,
                    'city' => $city,
                    'province' => $province
                ]
            ]);
            exit;
        } else {
            //检查电子邮件是否存在
            $params = [
                'email' => $email
            ];

            $user = $this->db->query('SELECT * FROM users WHERE email=:email', $params)->fetch();

            //如果查询到用户
            if ($user) {
                $errors['email'] = '该邮箱已注册! ';
                //重新加载注册页面
                loadView('users/create', [
                    'errors' => $errors
                ]);
                exit;
            }

            //创建用户1账户
            $params = [
                'name' => $name,
                'email' => $email,
                'city' => $city,
                'province' => $province,
                'password' => password_hash($password, PASSWORD_DEFAULT)
            ];
            $this->db->query('INSERT INTO  users (name,email,city,province,password) VALUES(:name,:email,:city,
            :province,:password)', $params);

            $userId = $this->db->conn->lastInsertId();

            Session::set('user', [
                'id' => $userId,
                'name' => $name,
                'email' => $email,
                'city' => $city,
                'province' => $province,
            ]);

            //创建用户成功后重定向
            redirect('/');
        }
    }
    /**
     * 注销用户
     */
    public function logout()
    {
        Session::clearAll();

        //获取cookie的参数
        $params = session_get_cookie_params();

        //删除cookie
        setcookie('PHPSESSID', '', time() - 86400, $params['path'], $params['domain']);
        //重定向
        redirect('/');
    }
    /**
     * 使用电子邮件和密码验证用户身份
     */
    public function authenticate()
    {
        $email = $_POST['email'];
        $password = $_POST['password'];

        //初始化
        $errors = [];

        //验证电子邮件格式
        if (!Validation::email($email)) {
            $errors['email'] = '请输入合法的邮箱地址! ';
        }

        //验证密码长度
        if (!Validation::string($password, 6, 50)) {
            $errors['password'] = '密码为至少6位! ';
        }

        if (!empty($errors)) {
            loadView('users/login', [
                'errors' => $errors
            ]);
            exit;
        }

        //准备查询参数
        $params = [
            'email' => $email
        ];

        //从数据库查询用户
        $user = $this->db->query('SELECT * FROM users WHERE email =:email', $params)->fetch();

        if (!$user) {
            $errors['email'] = '用户不存在或者密码错误! ';
            loadView('users/login', [
                'errors' => $errors
            ]);
            exit;
        }
        //验证密码是否正确
        if (!password_verify($password, $user->password)) {
            $errors['email'] = '用户不存在或者密码错误! ';
            loadView('users/login', [
                'errors' => $errors
            ]);
            exit;
        }

        //验证通过
        Session::set('user', [
            'id' => $user->id,
            'name' => $user->name,
            'email' => $user->email,
            'city' => $user->city,
            'province' => $user->province
        ]);

        redirect('/');
    }
}
